<script setup lang="ts">
import {onMounted, ref} from 'vue';
import number_scoll from './components/num-scoll/index.vue';
import activity from './components/activity/index.vue';
import userApi from '@/api/user.ts';
import articleApi from '@/api/article.ts'
import commentApi from '@/api/comment.ts'
import likeApi from '@/api/like.ts'
import collectApi from '@/api/collect.ts'
import useUserStore from '@/store/modules/user.ts';
import { getToken } from '@/utils/tokenUtils.ts';
import {
  EyeOutlined,
  LikeOutlined,
  CommentOutlined,
  FileTextOutlined,
  EditOutlined,
  SaveOutlined,
  LineChartOutlined,
  LoadingOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue';
import {MdCatalog, MdPreview} from "md-editor-v3";
import {useRouter} from 'vue-router';
import * as echarts from 'echarts';
const router = useRouter()

const userStore = useUserStore();
const isEdit = ref<boolean>(false); // 是否编辑
const fileList = ref<Array<any>>([]); // 文件列表
const user = ref({}); // 用户信息
onMounted(async () => {
  try {
    const result = await userStore.getInfo()
    user.value = result.data.user
  } catch (e) {
  }
})
// 处理头像上传
const handleChange = (event: any) => {
  if (event.file?.response?.code === 200) {
    user.value.avatar = event.file.response.data;
  }
};

// 编辑确认
const handleOk = async () => {
  const result = await userApi.modifyUser(user.value);
  if (result.code === 200) {
    await userStore.getInfo(); // 更新用户信息
    user.value = { ...userStore.userInfo }; // 重新赋值
  }
  isEdit.value = false; // 关闭弹窗
};
// 是否显示草稿
const isShowDraft = ref(false)
const draftList = ref([])
// 获取草稿列表
const getDraftList = async () => {
  const result = await articleApi.getDraftList()
  if (result.code === 200) {
    draftList.value = result.rows
  }
}
const publishList = ref([])
const getPublishList = async () => {
  const result = await articleApi.getPublishList()
  if (result.code === 200) {
    publishList.value = result.rows
  }
}
// 是否显示加载状态
const isShowLoadDraft = ref(false)
const isShowLoadPublish = ref(false)
const showDialog =async (value:string) => {
  if (value == 'draft') {
    isShowLoadDraft.value = true
    isShowDraft.value = true
    await getDraftList()
    isShowLoadDraft.value = false
  }
  else{
    isShowLoadPublish.value = true
    isShowPublish.value = true
    await getPublishList()
    isShowLoadPublish.value = false
  }
}
// 编辑草稿
const editDraft = (article:any) => {
  router.push({path:'editor',query: article})
}
// 删除草稿
const deleteDraft = (id:number) => {
  articleApi.deleteArticle(id)
  getDraftList()
}
// 是否显示已发布
const isShowPublish = ref(false)
const editPublish = (id:number) => {

}
const deletePublish = (id:number) => {
  articleApi.deleteArticle(id)
  getPublishList()
}
// markdown预览组件
const id = 'preview-only';
const text = ref();
const scrollElement = '.detail .right .ant-card'
const e = document.querySelector('.right .content .ant-card-body')
const isShowPreview = ref(false)
const previewContent = ref('')
const previewHandle = (content:string) => {
  previewContent.value = content
  isShowPreview.value = true
}
const option1 = {
  tooltip: { //鼠标悬浮上去的提示，不需要直接去掉tooltip
    trigger: 'axis',
  },
  xAxis: {
    type: "category",
    data: []
  },
  yAxis: {},
  series: [{
    data: [],
    type: "line",
  }]
}
const option2 = ref({
  tooltip: { //鼠标悬浮上去的提示，不需要直接去掉tooltip
    trigger: 'axis',
  },
  xAxis: {
    type: "category",
    data: []
  },
  yAxis: {},
  series: [{
    data: [],
    type: "line",
  }]
})
const option3 = ref({
  tooltip: { //鼠标悬浮上去的提示，不需要直接去掉tooltip
    trigger: 'axis',
  },
  xAxis: {
    type: "category",
    data: []
  },
  yAxis: {},
  series: [{
    data: [],
    type: "line",
  }]
})
const option4 = ref({
  tooltip: { //鼠标悬浮上去的提示，不需要直接去掉tooltip
    trigger: 'axis',
  },
  xAxis: {
    type: "category",
    data: []
  },
  yAxis: {},
  series: [{
    data: [],
    type: "line",
  }]
})
const isShowView1 = ref(false)
const total1 = ref(0)
const isShowView2 = ref(false)
const total2 = ref(0)
const isShowView3 = ref(false)
const total3 = ref(0)
const isShowView4 = ref(false)
const total4 = ref(0)
// 获取最近七天收藏数据
const getAddCollectHandler = async () => {
  const result = await collectApi.getAddCollectNum()
  option1.xAxis.data = result.data.map(item => item.name)
  const data = result.data.map(item => item.value)
  option1.series[0].data = data
  total1.value = result.data.reduce((pre,cur) => {
    return pre + cur.value
  },0)
}
// 获取最近七天点赞数据
const getAddLikeNumHandler = async () => {
  const result = await likeApi.getAddLikeNum()
  option2.value.xAxis.data = result.data.map(item => item.name)
  const data = result.data.map(item => item.value)
  option2.value.series[0].data = data
  total2.value = result.data.reduce((pre,cur) => {
    return pre + cur.value
  },0)
}
// 获取最近七天新增评论数
const getAddCommentNumHandler = async () => {
  const result = await commentApi.getAddCommentNum()
  option3.value.xAxis.data = result.data.map(item => item.name)
  const data = result.data.map(item => item.value)
  option3.value.series[0].data = data
  total3.value = result.data.reduce((pre,cur) => {
    return pre + cur.value
  },0)
}
// 获取最近七天文章发布数
const getAddArticleNumHandler = async () => {
  const result = await articleApi.getAddArticleNum()
  option4.value.xAxis.data = result.data.map(item => item.name)
  const data = result.data.map(item => item.value)
  option4.value.series[0].data = data
  total4.value = result.data.reduce((pre,cur) => {
    return pre + cur.value
  },0)
}
onMounted(() => {
  getAddCollectHandler()
  getAddLikeNumHandler();
  getAddCommentNumHandler()
  getAddArticleNumHandler()
})
const clickOverviewHandle = async (index) => {
  switch (index) {
    case 1:
      isShowView1.value = true
      break;
    case 2:
      isShowView2.value = true
      break;
    case 3:
      isShowView3.value = true
      break;
    case 4:
      isShowView4.value = true
      break;
  }
}

const pageInfo = ref({
  currentPage:1,
  pageSize:5
})

// 是否显示加载更多
const isLoadingDraftMore = ref(false)
const isLoadingPublishMore = ref(false)
const isShowDraftLoadingText = ref(false)
const isShowPublishLoadingText = ref(false)
const loadDraftMore =async () => {
  isLoadingDraftMore.value = true
  pageInfo.value.currentPage++
  const result = await articleApi.getDraftList(pageInfo.value)
  if (result.code == 200) {
    if (result.rows.length == 0) {
      pageInfo.value.currentPage--
      isShowDraftLoadingText.value = true
    }
    draftList.value = draftList.value.concat(result.rows)
  }
  isLoadingDraftMore.value = false
}

const loadPublishMore =async () => {
  isLoadingPublishMore.value = true
  pageInfo.value.currentPage++
  const result = await articleApi.getPublishList(pageInfo.value)
  if (result.code == 200) {
    if (result.rows.length == 0) {
      pageInfo.value.currentPage--
      isShowPublishLoadingText.value = true
    }
    publishList.value = publishList.value.concat(result.rows)
  }
  isLoadingPublishMore.value = false
}

// 重置分页信息
const resetPageInfo = () => {
  pageInfo.value.currentPage = 1
  pageInfo.value.pageSize = 5
}
// 关闭已发布回调
const closePublish = () => {
  isLoadingPublishMore.value = false
  isShowPublishLoadingText.value = false
  resetPageInfo()
}

// 关闭草稿弹窗回调
const closeDraft = () => {
  isLoadingDraftMore.value = false
  isShowDraftLoadingText.value = false
  resetPageInfo()
}
</script>

<template>
  <div class="personal">
    <a-card class="info" body-style="display:flex;justify-content:space-between;width:100%;">
      <img :src="userStore.userInfo.avatar ? userStore.userInfo.avatar : '/src/assets/avatar.jpg'" alt="" class="avatar">
      <div class="right">
        <div class="name"> {{ user.nickname ? user.nickname : user.username }}</div>
        <div class="content"> {{ user.aphorism }} </div>
        <div class="data">
          <div>
<!--            <div class="num">126</div>-->
            <number_scoll
                class="num"
              :number="user.totalArticleNum ? user.totalArticleNum : 0"
            ></number_scoll>
            <div>文章数</div>
          </div>
          <div>
            <number_scoll
                class="num"
                :number="user.totalWatchNum ? user.totalWatchNum : 0"
            ></number_scoll>
            <div>总阅读量</div>
          </div>
          <div>
            <number_scoll
                class="num"
                :number="user.totalFanNum ? user.totalFanNum : 0"
            ></number_scoll>
            <div>粉丝数</div>
          </div>
          <div>
            <number_scoll
                class="num"
                :number="user.totalLikeNum ? user.totalLikeNum : 0"
            ></number_scoll>
            <div>获赞数</div>
          </div>
        </div>
      </div>
      <a-button type="primary" @click="isEdit = true">编辑资料</a-button>
    </a-card>
<!--  编辑资料弹出框-->
    <a-modal v-model:open="isEdit" title="编辑资料" @ok="handleOk">
      <a-form style="max-width: 600px" :label-col="{ style: { width: '50px' } }" :wrapper-col="{ span: 30 }">
        <a-form-item label="头像">
          <a-upload
              name="file"
              list-type="picture-card"
              class="avatar-uploader content"
              :show-upload-list="false"
              :headers="{
                authorization: 'Bearer ' + getToken()
              }"
              action="dev-api/client/user/file/upload"
              @change="handleChange"
          >
            <img v-if="user.avatar" :src="user.avatar" alt="avatar" />
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">点击上传封面图</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="user.nickname"></a-input>
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-model:value="user.phoneNum"></a-input>
        </a-form-item>
        <a-form-item label="职位">
          <a-input v-model:value="user.position"></a-input>
        </a-form-item>
        <a-form-item label="格言">
          <a-input v-model:value="user.aphorism"></a-input>
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input v-model:value="user.email"></a-input>
        </a-form-item>
        <a-form-item label="性别" v-model:value="user.sex">
          <a-select >
            <a-select-option value="1">男</a-select-option>
            <a-select-option value="0">女</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="isEdit = false">取消</a-button>
        <a-button key="submit" type="primary" @click="handleOk">
          修改
        </a-button>
      </template>
    </a-modal>
<!--    数据概览-->
    <div class="overview">
      <a-card hoverable @click="clickOverviewHandle(1)">
        <div style="display: flex;justify-content: space-between">
          <EyeOutlined style="font-size: 30px;color: rgb(59, 130, 246)"/>
          <div class="month">
            近七天
          </div>
        </div>
        <div class="content">
          <number_scoll
              class="number"
              :number="total1"
          ></number_scoll>
          <div class="text">新增收藏</div>
        </div>
      </a-card>
      <a-modal v-model:open="isShowView1" body-style="height:300px">
        <template #footer></template>
        <v-chart :option="option1" autoresize/>
      </a-modal>

      <a-card hoverable  @click="clickOverviewHandle(2)">
        <div style="display: flex;justify-content: space-between">
          <LikeOutlined style="font-size: 30px;color: rgb(34, 197, 94)"/>
          <div class="month">
            近七天
          </div>
        </div>
        <div class="content">
          <number_scoll
              class="number"
              :number="total2"
          ></number_scoll>
          <div class="text">新增点赞</div>
        </div>
      </a-card>
      <a-modal v-model:open="isShowView2" body-style="height:300px">
        <template #footer></template>
        <v-chart :option="option2" autoresize/>
      </a-modal>

      <a-card hoverable  @click="clickOverviewHandle(3)">
        <div style="display: flex;justify-content: space-between">
          <CommentOutlined style="font-size: 30px;color: rgb(234, 179, 8)"/>
          <div class="month">
            近七天
          </div>
        </div>
        <div class="content">
          <number_scoll
            class="number"
            :number="total3"
        ></number_scoll>
          <div class="text">新增评论</div>
        </div>
      </a-card>
      <a-modal v-model:open="isShowView3" body-style="height:300px">
        <template #footer></template>
        <v-chart :option="option3" autoresize/>
      </a-modal>

      <a-card hoverable  @click="clickOverviewHandle(4)">
        <div style="display: flex;justify-content: space-between">
          <FileTextOutlined style="font-size: 30px;color: rgb(168, 85, 247)"/>
          <div class="month">
            近七天
          </div>
        </div>
        <div class="content">
          <number_scoll
            class="number"
            :number="total4"
        ></number_scoll>
          <div class="text">文章发布量</div>
        </div>
      </a-card>
      <a-modal v-model:open="isShowView4" body-style="height:300px">
        <template #footer></template>
        <v-chart :option="option4" autoresize/>
      </a-modal>
    </div>

<!--    底部-->
    <div class="other">
      <div class="left">
        <a-card
            style="background-color:rgb(249, 250, 251);border: 0"
            head-style="padding:0"
            body-style="display:flex;flex-direction:column;padding:0;gap:10px;"
            title="快捷操作">
          <a-card
              @click="$router.push('/editor')"
              body-style="display:flex;" hoverable>
            <EditOutlined class="icon-style" style="background-color:rgb(219, 234, 254); color: rgb(59, 130, 246)"/>
            <div class="content-right">
              <div class="title">写文章</div>
              <div class="content">开始创作新的内容</div>
            </div>
          </a-card>
          <a-card body-style="display:flex;"
                  @click="showDialog('draft')"
                  hoverable>
            <SaveOutlined class="icon-style" style="background-color:rgb(243, 244, 246);color: rgb(107, 114, 128)"/>
            <div class="content-right">
              <div class="title">草稿箱</div>
              <div class="content">4篇草稿待完成</div>
            </div>
          </a-card>
          <a-card body-style="display:flex;"
                  @click="showDialog('publish')"
                  hoverable>
            <CommentOutlined class="icon-style" style="background-color:rgb(220, 252, 231);color: rgb(34, 197, 94)"/>
            <div class="content-right">
              <div class="title">已发布</div>
              <div class="content">您已发布12篇博客</div>
            </div>
          </a-card>
          <a-card body-style="display:flex;" hoverable>
            <LineChartOutlined class="icon-style" style="background-color:rgb(243, 232, 255);color: rgb(168, 85, 247)"/>
            <div class="content-right">
              <div class="title">数据分析</div>
              <div class="content">查看详情统计数据</div>
            </div>
          </a-card>
        </a-card>
      </div>
      <div class="right">
        <a-card
            style="background-color:rgb(249, 250, 251);border: 0;height: 100%;"
            head-style="padding:0"
            body-style="overflow:scroll;height:100%;"
        >
          <template #title>
            最近活动
          </template>
          <activity></activity>
        </a-card>
      </div>
    </div>
<!--    // 草稿弹出框-->
    <a-modal
        :after-close="closeDraft"
        class="draft"
        v-model:open="isShowDraft"
        :body-style="{ 'padding': '0' ,'max-height':'500px','overflow': 'scroll'}"
        width="700px">
      <template #footer></template>
      <div class="item"
           v-if="draftList.length>0"
           v-for="(item,index) in draftList"
          :key="index"
       >
        <img :src="item.coverImg" alt="">
        <div class="middle">
          <div class="title">{{item.title}}</div>
          <div class="content">{{item.content}}</div>
        </div>
        <div class="right">
          <div class="time">{{item.updateTime || item.createTime}}</div>
          <div class="button">
            <a-tooltip title="预览" color="darkorange" placement="bottom">
              <EyeOutlined style="color: darkorange" @click="previewHandle(item.content)"/>
            </a-tooltip>
            <a-tooltip title="编辑" color="deepskyblue" placement="bottom">
              <FormOutlined style="color: deepskyblue" @click="editDraft(item)"/>
            </a-tooltip>
            <a-tooltip title="删除" color="darkred" placement="bottom">
              <a-popconfirm title="确认删除？"
                            @confirm="deleteDraft(item.id)"
                            ok-text="确认"
                            cancel-text="取消">
                <DeleteOutlined style="color: darkred"/>
              </a-popconfirm>
            </a-tooltip>
          </div>
        </div>
      </div>
      <div >
      </div>
      <div style="height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;">
        <a-spin v-if="isLoadingDraftMore"></a-spin>
        <div v-else-if="isShowDraftLoadingText" style="color: rgb(128,125,125)">没有更多了...</div>
        <a-button @click="loadDraftMore" v-else-if="!isLoadingDraftMore && !isShowDraftLoadingText && draftList.length > 0">加载更多</a-button>
      </div>
      <!--      展示空状态-->
      <a-empty v-if="draftList.length <= 0"/>
    </a-modal>

<!--    // 草稿预览弹出框-->
    <a-modal
        body-style="height:600px;overflow:scroll;"
        v-model:open="isShowPreview" width="1000px">
      <template #footer></template>
      <a-row>
<!--        <a-col :span="6">-->
<!--          <MdCatalog :editorId="id"-->
<!--                     :scrollElement="scrollElement" />-->
<!--        </a-col>-->
        <a-col :span="24">
          <!--      内容-->
          <MdPreview :id="id"
                     :modelValue="previewContent" />
        </a-col>
      </a-row>
    </a-modal>


<!--    // 发布弹出框-->
    <a-modal
        class="draft"
        :afterClose="closePublish"
        v-model:open="isShowPublish"
        :body-style="{ 'padding': '0' ,'max-height':'500px','overflow': 'scroll'}"
        width="700px">
      <template #footer></template>
      <div class="item"
           v-if="publishList.length>0"
           v-for="(item,index) in publishList"
           :key="index"
      >
        <img :src="item.coverImg" alt="">
        <div class="middle">
          <div class="title">{{item.title}}</div>
          <div class="content">{{item.content}}</div>
        </div>
        <div class="right">
          <div class="time">{{item.updateTime || item.createTime}}</div>
          <div class="button">
            <a-tooltip title="预览" color="darkorange" placement="bottom">
              <EyeOutlined style="color: darkorange" @click="previewHandle(item.content)"/>
            </a-tooltip>
            <a-tooltip title="编辑" color="deepskyblue" placement="bottom" v-if="false">
              <FormOutlined style="color: deepskyblue" @click="editPublish(item.id)"/>
            </a-tooltip>
            <a-tooltip title="删除" color="darkred" placement="bottom">
              <a-popconfirm title="确认删除？"
                            @confirm="deletePublish(item.id)"
                            ok-text="确认"
                            cancel-text="取消">
                <DeleteOutlined style="color: darkred"/>
              </a-popconfirm>
            </a-tooltip>
          </div>
        </div>
      </div>
      <div style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;">
        <a-spin v-if="isLoadingPublishMore"></a-spin>
        <div v-else-if="isShowPublishLoadingText" style="color: rgb(128,125,125)">没有更多了...</div>
        <a-button @click="loadPublishMore" v-else-if="!isLoadingPublishMore && !isShowDraftLoadingText && publishList.length > 0">加载更多</a-button>
      </div>
      <!--      展示空状态-->
      <a-empty v-if="publishList.length <= 0"/>
    </a-modal>
    <!--    // 发布预览弹出框-->
    <a-modal
        z-index="1001"
        body-style="height:600px;overflow:scroll;"
        v-model:open="isShowPreview" width="1000px">
      <template #footer></template>
      <a-row>
        <!--        <a-col :span="6">-->
        <!--          <MdCatalog :editorId="id"-->
        <!--                     :scrollElement="scrollElement" />-->
        <!--        </a-col>-->
        <a-col :span="24">
          <!--      内容-->
          <MdPreview :id="id"
                     :modelValue="previewContent" />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
}
.personal{
  overflow: auto;
  &::-webkit-scrollbar{
    display: none;
  }
  height: 100%;
  .info{
    height: 194px;
    display: flex;
    justify-content: space-between;
    .avatar{
      height: 120px;
      aspect-ratio: 1/1;
      border-radius: 50%;
      margin-right: 20px;
    }
    .right{
      flex: 1;
      .name{
        font-size: 26px;
        font-weight: 900;
      }
      .content{
        margin: 10px 0px 20px;
        color: rgb(107, 114, 129);
        font-size: 16px;
      }
      .data{
        display: flex;
        gap: 45px;
        .num{
          font-size: 26px;
          font-weight: 700;
        }
        >div{
          :last-child{
            color: rgb(107, 114, 129);
          }
        }
      }
    }
  }
  .overview{
    margin-top: 2.5%;
    height:215px;
    width: 100%;
    display: grid;
    grid-template-columns: repeat(4 ,1fr);
    gap: 24px;
    .month{
      color: rgb(119, 127, 152);
    }
    .content{
      margin-top: 10px;
      .text{
        color: rgb(175, 179, 187);
      }
      .number{
        font-size: 26px;
        font-weight: 700;
      }
    }
  }
  .other{
    display: flex;
    height: 440px;
    margin-top: 3%;
    gap: 25px;
    .left{
      flex: 0.98;
      display: flex;
      flex-direction: column;
      gap: 3%;
      .icon-style{
        background-color: darkgrey;
        padding: 10px;
        border-radius: 20%;
        font-size: 25px;
        margin-right: 15px;
      }
      .content-right{
        .title{
          font-size: 16px;
        }
        .content{
          color: rgb(134, 140, 151);
        }
      }
    }
    .right{
      //background-color: blue;
      flex: 2;
    }
  }

}
// 草稿箱
.draft ,.publish{
  max-height: 500px;
  .item{
    display: flex !important;
    justify-content: space-between;
    padding: 10px;
    border-radius: 5%;
    &:hover{
      transition: all .3s;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    img{
      height: 100px;
      aspect-ratio: 1/1;
      margin-right: 20px;
    }
    .title{
       font-size: 16px;
       font-weight: 600;
     }
    .middle{
      flex: 1;
      .content{
        overflow : hidden;
        text-overflow: ellipsis;//当对象内文本溢出时显示省略标记
        display: -webkit-box;
        -webkit-line-clamp:2;//这边的2指的是两行
        -webkit-box-orient: vertical;
      }
    }
    .right{
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .time{
        font-size: 12px;
        color: #999;
      }
      .button{
        display: flex;
        flex-shrink: 0;
        justify-content: right;
        gap: 10px;
        cursor: pointer;
      }
    }
  }
}
</style>
